export const env: any = 'production' // 线上环境
// export const env: any = 'debug' // 本地环境
const server_ip = '1.94.13.125'
const domain = '7anying.com.cn'
export const getBaseUrl = () => {
  if (env === 'production') {
    return `https://${domain || `${server_ip}:3001`}/7a/api`
  } else {
    return 'https://localhost:3001/7a/api'
  }
}
export const getBaseUrlBlog = () => {
  if (env === 'production') {
    return `https://${domain || server_ip}/home`
  } else {
    return 'https://localhost:3000/home'
  }
}

export interface RequestOptions {
  method?: 'GET' | 'POST'
  headers?: Record<string, string>
  body?: any
}

export async function request(url: string, options: RequestOptions = {}) {
  const { method = 'GET', headers, body } = options
  // const token = getCookie('blog_t_enc')
  const isFormData = typeof FormData !== 'undefined' && body instanceof FormData

  const finalHeaders: Record<string, string> = {
    // Authorization: `Bearer ${token}`,
    ...headers,
  }
  if (method === 'POST' && !isFormData) {
    finalHeaders['Content-Type'] = 'application/json'
  }

  const response = await fetch(url, {
    method,
    headers: finalHeaders,
    body:
      method === 'POST'
        ? isFormData
          ? (body as FormData)
          : JSON.stringify(body)
        : undefined,
  })
  // if (!response.ok) {
  //   throw new Error(`HTTP error! status: ${response.status}`)
  // }

  return response.json()
}

export const get = async (requestUrl: string, params?: Record<string, any>) => {
  const baseUrl = getBaseUrl()
  const url = new URL(baseUrl + requestUrl)
  if (params) {
    Object.keys(params).forEach((key) =>
      url.searchParams.append(key, params[key])
    )
  }
  return request(url.toString(), { method: 'GET' })
}

export const post = async (requestUrl: string, body: any) => {
  const baseUrl = getBaseUrl()
  return request(baseUrl + requestUrl, { method: 'POST', body })
}
